package com.kaithan.framework.common.util;

import java.util.regex.Pattern;

/**
 * 类描述：用于校验密码复杂度
 *
 * @author ZhuYin
 * @since 2025年02月21日
 */
public class PasswordStrengthChecker {

    /** 包含小写字母 */
    private static final String REGEX_LOWERCASE = ".*[a-z].*";
    /** 包含大写字母 */
    private static final String REGEX_UPPERCASE = ".*[A-Z].*";
    /** 包含数字 */
    private static final String REGEX_DIGIT = ".*\\d.*";
    /** 包含特殊字符 */
    private static final String REGEX_SPECIAL_CHAR = ".*[!@#$%^&*(),.?\":{}|<>].*";

    /**
     * 判断密码强度
     *
     * @param password 用户输入的密码
     * @return 返回密码强度等级（"弱"、"中"、"强"）
     */
    public static String checkPasswordStrength(String password) {
        if (password == null || password.isEmpty()) {
            return "无效密码";
        }

        // 密码强度评分
        int score = 0;

        // 检查密码长度
        int normalLength = 8;
        int longLength = 12;
        if (password.length() >= normalLength) {
            score++;
        }
        if (password.length() >= longLength) {
            score++;
        }

        // 检查是否包含小写字母
        if (Pattern.matches(REGEX_LOWERCASE, password)) {
            score++;
        }

        // 检查是否包含大写字母
        if (Pattern.matches(REGEX_UPPERCASE, password)) {
            score++;
        }

        // 检查是否包含数字
        if (Pattern.matches(REGEX_DIGIT, password)) {
            score++;
        }

        // 检查是否包含特殊字符
        if (Pattern.matches(REGEX_SPECIAL_CHAR, password)) {
            score++;
        }

        int weakScore = 2;
        int mediumScore = 4;
        // 根据评分返回密码强度等级
        if (score <= weakScore) {
            return "弱";
        } else if (score <= mediumScore) {
            return "中";
        } else {
            return "强";
        }
    }

    /**
     * 测试方法
     */
    public static void main(String[] args) {
        String[] passwords = {"abc", "abc123", "Abc123", "Abc123!", "StrongP@ssw0rd"};
        for (String password : passwords) {
            System.out.println("密码: " + password + " -> 强度: " + checkPasswordStrength(password));
        }
    }
}